<?php
class ModelArticleTerm extends BaseModel {

    protected function table(){
        return "wp_terms";
    }

    protected function primary_key_name(){
        return "term_id";
    }


    public function add($data, $extra = null) {

        $this->db->query("INSERT INTO " . $this->table() . " SET name = '{$data['name']}',image = '{$data['image']}'");

        $id = $this->db->getLastId();

        if(isset($extra) && isset($extra['taxonomy']))
            $this->db->query("INSERT INTO wp_term_taxonomy SET term_id = {$id},taxonomy = '{$extra['taxonomy']}' ");

        return $id;
    }
    public function edit($id, $data) {
        $this->db->query("UPDATE " . $this->table() . " SET name = '{$data['name']}',image = '{$data['image']}' WHERE {$this->primary_key_name()} = {$id}");

    }
    public function can_delete($id) {
        $query = $this->db->query("SELECT COUNT(*) as ret FROM wp_term_relationships a join wp_term_taxonomy b on a.term_taxonomy_id=b.term_taxonomy_id WHERE b.term_id = {$id}");
        return $query->row['ret'] == 0;
    }

    public function delete($id) {
        parent::delete($id);
        $this->db->query("DELETE FROM wp_term_taxonomy WHERE " . $this->primary_key_name() . " = '" . (int)$id . "'");
    }

    public function getList($data = array()) {
        $sql = "SELECT a.*,b.term_taxonomy_id  FROM " . DB_PREFIX . $this->table() . " a join wp_term_taxonomy b on a.term_id = b.term_id where b.taxonomy = '{$data['taxonomy']}'   ";

        $sort_data = array(
            $this->primary_key_name()
        );

        if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql .= " ORDER BY " . $data['sort'];
        } else {
            $sql .= " ORDER BY " . $sort_data[0];
        }

        if (isset($data['order']) && ($data['order'] == 'ASC')) {
            $sql .= " ASC";
        } else {
            $sql .= " DESC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if ($data['start'] < 0) {
                $data['start'] = 0;
            }

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }

            $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }

        $query = $this->db->query($sql);

        return $query->rows;
    }
}